package com.tanhua.api.mongo;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Long userId, Long friendId) {
        // 1、你添加他
        Query query = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        if (!mongoTemplate.exists(query, Friend.class)) {
            // 添加好友
            Friend friend = new Friend();
            friend.setCreated(System.currentTimeMillis());
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            mongoTemplate.save(friend);
        }

        // 2、他添加你
        query = Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        if (!mongoTemplate.exists(query, Friend.class)) {
            // 添加好友
            Friend friend = new Friend();
            friend.setCreated(System.currentTimeMillis());
            friend.setUserId(friendId);
            friend.setFriendId(userId);
            mongoTemplate.save(friend);
        }
    }

    @Override
    public PageBeanVo findByPage(Integer pageNum, Integer pageSize, Long userId) {

        // 分页查询
        Integer index = (pageNum - 1) * pageSize;

        Query query = Query.query(Criteria.where("userId").is(userId)).skip(index).limit(pageSize);

        List<Friend> friendList = mongoTemplate.find(query, Friend.class);

        Long counts = mongoTemplate.count(query, Friend.class);

        return new PageBeanVo(pageNum, pageSize, counts, friendList);
    }

    @Override
    public void remove(Long userId, Long friendId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        mongoTemplate.remove(query,Friend.class);

    }
}
